package cn.sczhyt.modules.app.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

public class FileReadOnlineUtils {
    /**
     * 文件在线阅读
     * @param response
     * @param filePath
     * @param fileName
     * @param type
     * @throws IOException
     */
    public static void fileReadOnline(HttpServletResponse response,
                               String filePath,
                               String fileName,
                               String type) throws IOException {
        //设置响应内容类型为PDF类型
        response.setContentType("application/"+type);

        //获取文件详情
        File file = new File(filePath);
        if (!file.exists()) {
            response.sendError(404, "File not found!");
            return;
        }

        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        byte[] bs = new byte[1024];
        int len;
        response.reset(); // 非常重要
        URL url = new URL("file:///" + filePath);

        String contentType = url.openConnection().getContentType();
        response.setContentType(contentType);
        //在线打开
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));

        //不在网页中打开，而是直接下载该文件，下载后的文件名为“Example.pdf”
        //response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

}
